package com.yanhao.viewmode

import androidx.lifecycle.*
import com.yanhao.bean.ProjectInfo
import com.yanhao.etx.error
import com.yanhao.repository.ProjectInfoRepository
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

class ProjectInfoModel(private val resp: ProjectInfoRepository) : BaseViewModel() {

    private var _index = MutableLiveData<Int>(1)
    val index: LiveData<Int>
        get() = _index

    private var _projectInfos = MutableLiveData<MutableList<ProjectInfo>>()
    val projectInfos: LiveData<MutableList<ProjectInfo>>
        get() = _projectInfos

    private var _isRefresh = MutableLiveData<Boolean>(false)
    val isRefresh: LiveData<Boolean>
        get() = _isRefresh


    fun getProjectTrees(cid: Int) {
        viewModelScope.launch {
            flow {
                val result = resp.getProjectTreeInfo(_index.value ?: 1, cid)
                emit(result)
            }.catch { e: Throwable ->
                errorCatch(e)
            }.onStart {
                _isRefresh.value = true
            }.onCompletion {

            }.collect {
                if (it.errorCode == 0) {
                    val temps = it.data.datas
                    _projectInfos.value = temps
                } else {
                    _errorMsg.value = it.errorMsg
                }
            }
        }
    }

    fun getProjectTreeMores(cid: Int) {
        viewModelScope.launch {
            flow {
                val result = resp.getProjectTreeInfo(_index.value ?: 1, cid)
                emit(result)
            }.catch { e: Throwable ->
                errorCatch(e)
            }.onStart {
                _isRefresh.value = false
            }.onCompletion {

            }.collect {
                if (it.errorCode == 0) {
                    _projectInfos.value = it.data.datas
//                    val temp = it.data.datas
//                    val list = _projectInfos.value
//                    list?.addAll(temp)
//                    list?.let {
//                        _projectInfos.value = it
//                    }
                } else {
                    _errorMsg.value = it.errorMsg
                }
            }
        }
    }



    fun refreshData(cid: Int) {
        _index.value = 1
        getProjectTrees(cid)
    }

    fun onLoadMoreData(cid: Int) {
        val index = _index.value ?: 1
        val result = index.plus(1)
        _index.value = result
        getProjectTreeMores(cid)
    }

}

class ProjectInfoModelFactory : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(ProjectInfoModel::class.java)) {
            return ProjectInfoModel(resp = ProjectInfoRepository()) as T
        }
        throw IllegalArgumentException("不能找到 HomeFgRepository")
    }

}